﻿using System;
using System.Collections.Generic;
using Comm;

namespace QuotePoll
{
    /// <summary>
    /// A class to poll the MetaTrader Server
    /// </summary>
    public class QuoteClass
    {
        private readonly string _host;
        private readonly int _port;
        private readonly string _symbol;
        private double _ask;
        private double _bid;
        private DateTime _dateTime;


        /// <summary>
        /// Initializes a new instance of the <see cref="QuoteClass"/> class.
        /// </summary>
        /// <param name="symbol">The symbol to check</param>
        /// <param name="host">The MetaTrader host</param>
        /// <param name="port">The port of the MetaTrader server.</param>
        public QuoteClass(String symbol, string host, int port)
        {
            _symbol = symbol;
            _host = host;
            _port = port;

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="QuoteClass"/> class.
        /// </summary>
        /// <param name="symbol">The symbol to check</param>
        /// <param name="serverFileName">Path to the MetaTrader server file(srv).</param>
        public QuoteClass(String symbol, String serverFileName)
        {
            var keyValuePair = HostAndPort.Parse(serverFileName);
            _symbol = symbol;
            _host = keyValuePair.Key;
            _port = keyValuePair.Value;

        }

        public DateTime ServerDateTime
        {
            get { return _dateTime;  }
        }

        public double Ask
        {
            get { return _ask; }
        }

        public double Bid
        {
            get { return _bid; }
        }

        /// <summary>
        /// Updates the quotes.
        /// </summary>
        /// <returns>Whether successful</returns>
        public bool UpdateQuotes()
        {
            var retValue = false;
            var quoteText = "";

            var mSt = new Telnet(_host, _port, 20);
            if (mSt.Connect() == false)
            {
                Console.WriteLine("");
                Console.WriteLine("Error: ");
                Console.WriteLine("Timeout connecting to: " + _host);
                Console.WriteLine("");
            }
            else
            {
                try
                {
                    mSt.SendAndWait("WINFO", "MetaTrader");
                    mSt.SendAndWait("QUOTES-" + _symbol + ",", _symbol);

                    quoteText = mSt.FindStringBetween(_symbol + " ", "\n",
                                                      "Error: Quote not obtained");
                }
                catch (Exception)
                {
                }


                try
                {
                    if (quoteText.IndexOf(" ") > 0)
                    {
                        _bid = Convert.ToDouble(quoteText.Substring(0, quoteText.IndexOf(" ")));
                        retValue = true;
                    }
                }
                catch (FormatException)
                {
                    Console.WriteLine("Unable to convert '{0}' to a Double.",
                                      quoteText.Substring(0, quoteText.IndexOf(" ")));
                }
                catch (OverflowException)
                {
                    Console.WriteLine("'{0}' is outside the range of a Double.",
                                      quoteText.Substring(0, quoteText.IndexOf(" ")));
                }

                try
                {
                    if ((quoteText.Length - quoteText.IndexOf(" ")) > 0 && quoteText.IndexOf(" ") > 0)
                    {
                        var bidString = quoteText.Substring(quoteText.IndexOf(" ") + 1,
                                                              quoteText.IndexOf(" ", quoteText.IndexOf(" ") + 1) - quoteText.IndexOf(" "));

                        _ask =
                            Convert.ToDouble(bidString);
                        retValue = true;
                    }
                }
                catch (FormatException)
                {
                    Console.WriteLine("Unable to convert '{0}' to a Double.",
                                      quoteText.Substring(quoteText.IndexOf(" "),
                                                          quoteText.Length - quoteText.IndexOf(" ")));
                }
                catch (OverflowException)
                {
                    Console.WriteLine("'{0}' is outside the range of a Double.",
                                      quoteText.Substring(quoteText.IndexOf(" "),
                                                          quoteText.Length - quoteText.IndexOf(" ")));
                }
                try
                {
                    
                    if ((quoteText.Length - quoteText.IndexOf(DateTime.Now.Year.ToString())) > 0 && quoteText.IndexOf(DateTime.Now.Year.ToString()) > 0)
                    {
                        var dateString = quoteText.Substring(quoteText.IndexOf(DateTime.Now.Year.ToString()), quoteText.Length - quoteText.IndexOf(DateTime.Now.Year.ToString()));
                        _dateTime = DateTime.Parse(dateString);
                        retValue = true;
                    }
                }
                catch (FormatException)
                {
                    Console.WriteLine("Unable to convert to a DateTime.");
                }
                
                mSt.SendMessage("QUIT");
            }

            return (retValue);
        }

        
    }
}